package com.crl.ui.core
{
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	
	
	/**
	 * 渲染管理器;
	 * @author crl
	 * 
	 */	
	public class RenderManager
	{
		private var _stage:Stage;
		private var timer:Timer;
		private var _queue:Dictionary;
		public function RenderManager()
		{
			_queue=new Dictionary(true);
			
			timer = new Timer(19, 1);
			timer.addEventListener(TimerEvent.TIMER_COMPLETE, timerRender);
		}
		
		private static var instance:RenderManager;
		public static function getInstance():RenderManager{
			if(instance==null){
				instance=new RenderManager();
			}
			return instance;
		}
		
		public function setup(stage:Stage):void{
			this._stage=stage;
		}
		
		private function timerRender(event:TimerEvent):void{
			doValidation();
			event.updateAfterEvent();
		}
		
		public function addToQueue( instance : IRenderable ) : void{
			if(_queue[instance])return;
			
			_queue[instance]=true;
			if(_stage==null){
				timer.reset();
				timer.start();
			}else{
				_stage.addEventListener(Event.RENDER, doValidation, false, 0, true);
				_stage.invalidate();
			}
		}
		
		private function doValidation(event:Event=null):void{
			if(event){
				var stage:Stage=event.currentTarget as Stage;
				stage.removeEventListener(Event.RENDER, doValidation);
			}
			
			var instance:IRenderable;
			for( var key:* in _queue) {
				instance=key;
				instance.render();
				_queue[instance]=null;
				delete _queue[instance];
			}
		}
	}
}